<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form size="small" :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
               label-width="120px">
        <el-form-item label="商铺列表" prop="shopId">
          <el-select v-model="dataForm.shopId" @change="shopChange">
            <el-option
              v-for="(item,index) in shopList"
              :key="item.id"
              :label="item.shopName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户" prop="userId" v-if="!dataForm.id">
          <el-input v-model="dataForm.userId" placeholder="用户id" disabled></el-input>
          <div><span v-if="dataForm.userId" style="margin-right: 20px">{{dataForm.userName}}</span>
            <el-button type="text" @click="openUserDialog">选择关联用户</el-button>
          </div>

        </el-form-item>
        <el-form-item label="配送员姓名" prop="deName">
          <el-input v-model="dataForm.deName" placeholder="配送员姓名"></el-input>
        </el-form-item>
        <el-form-item label="配送员电话号码" prop="dePhone">
          <el-input v-model="dataForm.dePhone" placeholder="配送员电话号码"></el-input>
        </el-form-item>
        <el-form-item label="服务类目" prop="deServicesValue">
          <el-select v-model="dataForm.deServicesValue" @change="merTypeChange">
            <el-option
              v-for="(item,index) in merTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="currentType==3" label="品牌类型选择" prop="deBankName">
          <el-button type="text" @click="handlerOpenCateDialog">选择维修分类</el-button>
          <el-table
            :data="cateListChecked"
            style="width: 100%">
            <el-table-column
              prop="name"
              label="分类名称"
              width="180">
            </el-table-column>
            <el-table-column
              label="操作"
              width="200">
              <template slot-scope="scope">
                <el-button type="text" @click="handlerDelCate(scope.row, scope.$index)" size="small">删除</el-button>
                <el-button type="text" @click="handlerOpenBrandDialog(scope.row)" size="small">品牌列表</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="开户行姓名" prop="deBankName">
          <el-input v-model="dataForm.deBankName" placeholder="开户行姓名"></el-input>
        </el-form-item>
        <el-form-item label="开户行" prop="deBank">
          <el-input v-model="dataForm.deBank" placeholder="开户行"></el-input>
        </el-form-item>
        <el-form-item label="银行卡号" prop="deBankCard">
          <el-input v-model="dataForm.deBankCard" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="deSort">
          <el-input v-model="dataForm.deSort" placeholder="排序"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false" size="small">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" size="small">确定</el-button>
    </span>
    </el-dialog>


    <el-dialog
      title="关联用户"
      :visible.sync="dialogUserVisible"
      width="40%"
      :before-close="handleUserDialogClose">
      <el-table :data="userList">
        <el-table-column label="昵称" prop="userName"></el-table-column>
        <el-table-column label="手机号" prop="userPhone"></el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="relatedUser(scope.row)">关联</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="userList" style="margin-top: 20px;text-align: right">
        <el-pagination
          @current-change="currentChangeHandle"
          :current-page="page.currentPage"
          :page-size="page.pageSize"
          :total="page.total"
          layout="total, prev, pager, next">
        </el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleUserDialogClose" size="small">取 消</el-button>
      </span>
    </el-dialog>


    <el-dialog
      title="选择分类"
      :visible.sync="cateDialogVisible"
      width="40%">
      <el-table :data="cateList">
        <el-table-column label="分类名称" prop="name"></el-table-column>
        <el-table-column label="排序" prop="sort"></el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handlerCateSelect(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>


    <!--    品牌对话框-->
    <el-dialog
      title="品牌列表"
      :visible.sync="dialogBrandVisible">
      <el-table :data="brandList" @selection-change="handleSelectionBrandChange"  ref="multipleBrandTable">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column label="品牌名称" prop="name"></el-table-column>
        <el-table-column label="排序" prop="sort"></el-table-column>
      </el-table>
    </el-dialog>
  </div>

</template>

<script>
  import {addObj, updateObj, delObj, fetchList, getObj} from '@/api/delivery/deliveryman'
  import {fetchCateTree} from '@/api/merchantservices/category'
  import {getAllShops} from '@/api/shop/shops'
  import {getUserListByNoDeliveryman} from '@/api/usercenter/user'
  import {getMerTypeByShopId} from '@/api/shop/shopservicestype'

  export default {
    data() {
      return {
        visible: false,
        shopList: [],
        userList: [],
        merTypeList: [],
        cateList: [],
        cateListChecked: [],
        cateIdListChecked: [],
        brandIdListChecked: [],
        brandList: [],
        dialogUserVisible: false,
        cateDialogVisible: false,
        dialogBrandVisible: false,
        currentCate: {},
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        currentType: '', //当前选中的type值
        dataForm: {
          id: 0,
          shopId: '',
          userId: '',
          deName: '',
          dePhone: '',
          deNickname: '',
          deStartTime: '',
          deEndTime: '',
          deServicesValue: '',
          deBankName: '',
          deBank: '',
          deBankCard: '',
          deSort: 100,
        },
        dataRule:
          {
            shopId: [
              {required: true, message: '配送员所属商铺不能为空', trigger: 'blur'}
            ],
            userId:
              [
                {required: true, message: '用户id不能为空', trigger: 'blur'}
              ],
            deName:
              [
                {required: true, message: '配送员姓名不能为空', trigger: 'blur'}
              ],
            dePhone:
              [
                {required: true, message: '配送员电话号码不能为空', trigger: 'blur'}
              ],
            deServicesValue:
              [
                {required: true, message: '服务类目不能为空', trigger: 'blur'}
              ],
            deBankName:
              [
                {required: true, message: '开户行姓名', trigger: 'blur'}
              ],
            deBank:
              [
                {required: true, message: '开户行不能为空', trigger: 'blur'}
              ],
            deBankCard:
              [
                {required: true, message: '不能为空', trigger: 'blur'}
              ],
            deSort:
              [
                {required: true, message: '排序不能为空', trigger: 'blur'}
              ]
          }
      }
    }
    ,
    methods: {
      init(id) {
        this.dataForm.id = id || 0
        this.cateListChecked = []
        this.cateIdListChecked = []
        this.brandList = []
        this.brandIdListChecked = []
        this.shopList = []
        this.merTypeList = []
        this.currentType = ''
        this.visible = true
        this.dataForm.userId = ''
        this.getShopList()
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            getObj(this.dataForm.id)
              .then(res => {
                let hqdeliveryman = res.data.data
                this.dataForm.shopId = hqdeliveryman.shopId
                this.dataForm.userId = hqdeliveryman.userId
                this.dataForm.deName = hqdeliveryman.deName
                this.dataForm.dePhone = hqdeliveryman.dePhone
                this.dataForm.deNickname = hqdeliveryman.deNickname
                this.dataForm.deServicesValue = hqdeliveryman.deServicesValue
                this.dataForm.deBankName = hqdeliveryman.deBankName
                this.dataForm.deBank = hqdeliveryman.deBank
                this.dataForm.deBankCard = hqdeliveryman.deBankCard
                this.dataForm.deSort = hqdeliveryman.deSort


                // 设置维修分类列表
                this.cateListChecked = hqdeliveryman.categories
                if (this.cateListChecked && this.cateListChecked.length > 0) {
                  let exids = ''
                  for (let i = 0; i < this.cateListChecked.length; i++) {
                    exids += this.cateListChecked[i].id + ','
                  }
                  this.getCateList(this.dataForm.shopId, this.dataForm.deServicesValue, exids)
                }

                // 获取当前的类型
                this.$http({
                  url: this.$http.adornUrl("/merchantservices/merservicestype/" + this.dataForm.deServicesValue),
                  method: 'get'
                }).then(res => {
                  this.currentType = res.data.data.type
                })


                //请求当前类型
                let data = new FormData()
                data.append('shopId', this.dataForm.shopId)
                getMerTypeByShopId(data)
                  .then(res => {
                    this.merTypeList = res.data.data
                  })

              })
          }
        })
      }
      ,
      getShopList() {
        const params = new FormData()
        params.append('shopId', this.$store.state.user.shopId)
        getAllShops(params)
          .then((res) => {
            this.shopList = res.data.data
          })
      }
      ,
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.id) {
              //更新
              this.updateDeliveryman()
            } else {
              //增加
              this.saveDeliveryman()
            }
          }
        })
      }
      ,
      saveDeliveryman() {
        const data = new FormData()
        data.append('userId', this.dataForm.userId)
        data.append('deName', this.dataForm.deName)
        data.append('dePhone', this.dataForm.dePhone)
        data.append('shopId', this.dataForm.shopId)
        data.append('deServicesValue', this.dataForm.deServicesValue)
        data.append('deBank', this.dataForm.deBank)
        data.append('deBankName', this.dataForm.deBankName)
        data.append('deBankCard', this.dataForm.deBankCard)
        if (this.currentType == 3) {
          if (!this.cateListChecked || this.cateListChecked.length <= 0) {
            this.$message.error('请选择维修分类')
            return
          }
          let cateBrand = []
          for (let i = 0; i < this.cateListChecked.length; i++) {
            let obj = {}
            let brands = this.cateListChecked[i].brands
            obj.cate = this.cateListChecked[i].id
            if (brands && brands.length > 0) {
              let brandIds = []
              for (let j = 0; j < brands.length; j++) {
                brandIds.push(brands[j].id)
              }
              obj.value = brandIds
            } else {
              obj.value = []
            }
            cateBrand.push(obj)
          }
          data.append('jsonStr', JSON.stringify(cateBrand))
        }
        addObj(data).then(data => {
          this.visible = false
          this.$message({
            showClose: true,
            message: '添加成功',
            type: 'success'
          })
          this.dataForm = {}
          this.$emit('refreshDataList')
        }).catch(res => {
        })
      },
      updateDeliveryman() {
        const data = new FormData()
        data.append('id', this.dataForm.id)
        data.append('userId', this.dataForm.userId)
        data.append('deName', this.dataForm.deName)
        data.append('dePhone', this.dataForm.dePhone)
        data.append('shopId', this.dataForm.shopId)
        data.append('deServicesValue', this.dataForm.deServicesValue)
        data.append('deBank', this.dataForm.deBank)
        data.append('deBankName', this.dataForm.deBankName)
        data.append('deBankCard', this.dataForm.deBankCard)
        if (this.currentType == 3) {
          if (this.cateListChecked.length <= 0) {
            this.$message.error('请选择维修分类')
            return
          }

          let cateBrand = []
          for (let i = 0; i < this.cateListChecked.length; i++) {
            let obj = {}
            let brands = this.cateListChecked[i].brands
            obj.cate = this.cateListChecked[i].id
            if (brands && brands.length > 0) {
              let brandIds = []
              for (let j = 0; j < brands.length; j++) {
                brandIds.push(brands[j].id)
              }
              obj.value = brandIds
            } else {
              obj.value = []
            }
            cateBrand.push(obj)
          }


          data.append('jsonStr', JSON.stringify(cateBrand))
        }
        // return
        updateObj(data).then(data => {
          this.visible = false
          this.$message({
            showClose: true,
            message: '更新成功',
            type: 'success'
          })
          this.dataForm = {}
          this.$emit('refreshDataList')
        }).catch(res => {
        })
      }
      ,
      shopChange(val) {
        this.currentType = ''
        this.merTypeList = []
        this.dataForm.deServicesValue = ''
        if (val) {
          let data = new FormData()
          data.append('shopId', val)
          getMerTypeByShopId(data)
            .then(res => {
              this.cateListChecked = []
              this.merTypeList = res.data.data
            })
        }
      }
      ,
      //关闭关联用户弹窗
      handleUserDialogClose() {
        this.dialogUserVisible = false
      }
      ,
      //关联用户
      relatedUser(row) {
        this.dataForm.userName = row.userName
        this.dataForm.userId = row.id
        this.dialogUserVisible = false
      }
      ,
      currentChangeHandle(val) {
        this.page.currentPage = val
        this.getUserList()
      }
      ,
      //打开关联用户对话框
      openUserDialog() {
        this.dialogUserVisible = true
        this.getUserList()
      }
      ,
      getUserList() {
        this.tableLoading = true
        const data = new FormData()
        data.append('currentPage', this.page.currentPage)
        data.append('size', this.page.pageSize)
        getUserListByNoDeliveryman(data).then(response => {
          this.userList = response.data.data.list
          this.page.total = response.data.data.totalCount
          this.tableLoading = false
        })
      }
      ,
      // 选择服务类型改变方法
      merTypeChange(val) {
        if (val) {
          // 获取当前的类型
          for (let i = 0; i < this.merTypeList.length; i++) {
            if (this.merTypeList[i].id == val) {
              this.currentType = this.merTypeList[i].type
            }
          }
        }
      }
      ,
      handlerOpenCateDialog() {
        // 打开选择分类列表
        let exids = ''
        if (this.cateListChecked && this.cateListChecked.length > 0) {
          for (let i = 0; i < this.cateListChecked.length; i++) {
            exids += this.cateListChecked[i].id + ','
          }
        }

        this.getCateList(this.dataForm.shopId, this.dataForm.deServicesValue, exids)
        this.cateDialogVisible = true
      },
      getCateList(shopId, merSerTypeId, exIds) {
        // const data = new FormData()
        // data.append('merSerTypeId', merSerTypeId ? merSerTypeId : null)
        // data.append('shopId', shopId)
        // data.append('exIds', exIds)
        fetchCateTree({'merSerTypeId' : merSerTypeId ? merSerTypeId : null, 'shopId': shopId, 'exIds': exIds}).then(response => {
          this.cateList = response.data.data;
        });
      },

      // 打开品牌列表
      handlerOpenBrandDialog(row) {
        this.currentCate = row
        this.dialogBrandVisible = true
        // 获取对应的品牌
        let brandTypeId = row.id
        if (brandTypeId) {
          this.$http({
            url: this.$http.adornUrl('/merchantservices/category/getChildCateList/' + brandTypeId),
            method: 'get',
            params: this.$http.adornParams({
              'parentId': brandTypeId
            })
          }).then(res => {
            this.dialogBrandVisible = true
            this.brandList = res.data.data
            let brands = this.currentCate.childCates
            if (brands && brands.length > 0) {
              for (let i = 0; i < brands.length; i++) {
                for (let j = 0; j < this.brandList.length; j++) {
                  if (brands[i].brandId == this.brandList[j].id) {
                    this.$nextTick(() => {
                      this.$refs.multipleBrandTable.toggleRowSelection(this.brandList[j],true);
                    })
                  }
                }
              }
            }

          })
        }
      },
      // 删除维修分类
      handlerDelCate(row, index) {
        let _this = this
        this.$confirm('是否确认删除ID为' + row.id, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          _this.cateListChecked.splice(index, 1)
        }).then(data => {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
        }).catch(function (err) {

        })
      },
      handlerCateSelect(row) {
        this.cateIdListChecked.push(row.id)
        if (this.cateListChecked && this.cateListChecked.length > 0) {
          for (let i = 0; i < this.cateListChecked.length; i++) {
            if (this.cateListChecked[i].id == row.id) {
              this.$message.error('已经加入该分类')
              return
            }
          }
        }


        this.cateListChecked.push(row)

        this.cateDialogVisible = false
      },
      handleSelectionBrandChange(val) {
        this.currentCate.brands = val
      }
    }
  }
</script>
